package com.tuishan.myapplication.Views.Fragment;

import android.Manifest;
import android.app.Fragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.tuishan.myapplication.Base.BaseContest;
import com.tuishan.myapplication.BuildConfig;
import com.tuishan.myapplication.Custom.LoadingView;
import com.tuishan.myapplication.MainActivity;
import com.tuishan.myapplication.Model.RegisterModel;
import com.tuishan.myapplication.R;
import com.tuishan.myapplication.Servers.BaseCallback;
import com.tuishan.myapplication.Servers.OkHttpHelper;
import com.tuishan.myapplication.Servers.UrlRouter;
import com.tuishan.myapplication.Utils.QiNiuFileUtils;
import com.tuishan.myapplication.Utils.QiNiuUtils;
import com.zhy.base.fileprovider.FileProvider7;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.WeakHashMap;

import cn.qqtheme.framework.picker.OptionPicker;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.http.Url;

import static android.app.Activity.RESULT_OK;

/**
 * <pre>
 *     time   : 2021/04/17
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class Fragment_Add extends Fragment implements View.OnClickListener {
    SimpleDraweeView send_photo_bg;
    ImageView send_add_bg;
    RelativeLayout Photo_btn;

    Button send_add_btn;
    Button add_type_btn;
    Button add_usage_btn;
    EditText add_name_edit, add_remarks_edit, add_account_edit;
    String imageName;
    UploadManager uploadManager;
    LoadingView Loading;
    //1生活 2学习 3服饰 4食品 5家具 6其他
    String[] TypeList = new String[]{
            "生活", "学习", "服饰", "食品", "家具", "其他"
    };
    int TypeIndex = 0;
    //1全新 2几乎全新 3轻微使用 4正常使用 5明显使用
    String[] UsageList = new String[]{
            "全新", "几乎全新", "轻微使用", "正常使用", "明显使用"
    };
    int UsageTypeIndex = 0;

    // 拍照的requestCode
    private static final int CAMERA_REQUEST_CODE = 0x00000010;
    // 申请相机权限的requestCode
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
    /**
     * 用于保存拍照图片的uri
     */
    private Uri mCameraUri;

    /**
     * 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
     */
    private String mCameraImagePath;

    /**
     * 是否是Android 10以上手机
     */
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_layout, container, false);
        send_photo_bg = view.findViewById(R.id.send_photo_bg);
        send_add_bg = view.findViewById(R.id.send_add_bg);
        send_add_btn = view.findViewById(R.id.send_add_btn);
        Photo_btn = view.findViewById(R.id.Photo_btn);
        add_type_btn = view.findViewById(R.id.add_type_btn);

        add_usage_btn = view.findViewById(R.id.add_usage_btn);
        add_name_edit = view.findViewById(R.id.add_name_edit);
        add_remarks_edit = view.findViewById(R.id.add_remarks_edit);
        add_account_edit = view.findViewById(R.id.add_account_edit);

        Loading = new LoadingView(getActivity());
        Photo_btn.setOnClickListener(this);
        add_type_btn.setOnClickListener(this);
        add_usage_btn.setOnClickListener(this);
        send_add_btn.setOnClickListener(this);
        send_add_bg.setVisibility(View.VISIBLE);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                send_photo_bg.setImageURI(mCameraUri);
                send_add_bg.setVisibility(View.INVISIBLE);
            } else {
                ToastUtils.showShort("取消");
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.Photo_btn:
                takePhotoNoCompress();
                break;
            case R.id.send_add_btn:
                UpQiNiu(UriUtils.uri2Bytes(mCameraUri), QiNiuUtils.GetQiNiuToken());
                break;
            case R.id.add_type_btn:
                ShowTypePicker();
                break;
            case R.id.add_usage_btn:
                UsagePicker();
                break;
        }
    }

    //类型选择器
    private void UsagePicker() {
        OptionPicker picker = new OptionPicker(getActivity(), UsageList);
        picker.setOffset(2);
        picker.setSelectedIndex(1);
        picker.setTextSize(24);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                LogUtils.e("选择类型：" + index);
                UsageTypeIndex = index + 1;
                add_usage_btn.setText(UsageList[index]);
            }
        });
        picker.show();
    }

    //类型选择器
    private void ShowTypePicker() {
        OptionPicker picker = new OptionPicker(getActivity(), TypeList);
        picker.setOffset(2);
        picker.setSelectedIndex(1);
        picker.setTextSize(24);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                LogUtils.e("选择类型：" + index);
                TypeIndex = index + 1;
                add_type_btn.setText(TypeList[index]);
            }
        });
        picker.show();
    }

    public void takePhotoNoCompress() {
        // 判断SDK是否>=23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA}, 123);
            } else {
                openCamera();
            }
        } else {
            openCamera();
        }
    }


    /**
     * 调起相机拍照
     */
    private void openCamera() {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断是否有相机
        if (captureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            File photoFile = null;
            Uri photoUri = null;

            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri();
            } else {
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (photoFile != null) {
                    mCameraImagePath = photoFile.getAbsolutePath();
                    System.out.println("path = " + mCameraImagePath);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0到9.0
                        //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri 如：content://
                        photoUri = FileProvider.getUriForFile(getActivity(),
                                "com.tuishan.myapplication.FileProvider", photoFile);
                    } else {//7.0以下, 如：file://
                        photoUri = Uri.fromFile(photoFile);
                    }
                }
            }

            LogUtils.e("photoUri = " + photoUri);
            mCameraUri = photoUri;
            if (photoUri != null) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    List<ResolveInfo> resInfoList = getActivity().getPackageManager()
                            .queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        getActivity().grantUriPermission(packageName, photoUri,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                }

                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     *
     * @return 图片的uri
     */
    private Uri createImageUri() {
        //设置保存参数到ContentValues中
        ContentValues contentValues = new ContentValues();
        //设置文件名
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() + "");
        //兼容Android Q和以下版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
            //TODO RELATIVE_PATH是相对路径不是绝对路径;照片存储的地方为：内部存储/Pictures/preventpro
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/preventpro");
        }
        //设置文件类型
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
        //执行insert操作，向系统文件夹中添加文件
        //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
        Uri uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        return uri;

    }

    /**
     * 创建保存图片的文件
     *
     * @return
     * @throws IOException
     */
    private File createImageFile() throws IOException {
        imageName = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date()) + ".jpg";
        File storageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "Pictures" + File.separator + "abc");
        if (!storageDir.exists()) storageDir.mkdirs();

        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }


    //上传图片
    private void UpQiNiu(byte[] file,  String uploadToken) {
        if (send_add_bg.getVisibility() == View.VISIBLE) {
            ToastUtils.showShort("请选择图片");
            return;
        }
        if (StringUtils.isEmpty(add_name_edit.getText().toString().trim())) {
            Toast.makeText(getActivity(), "请输入商品名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(add_remarks_edit.getText().toString().trim())) {
            Toast.makeText(getActivity(), "请输入描述", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(add_account_edit.getText().toString().trim())) {
            Toast.makeText(getActivity(), "请输入价格", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TypeIndex == 0) {
            ToastUtils.showShort("请选择商品类型");
            return;
        }
        if (UsageTypeIndex == 0) {
            ToastUtils.showShort("请选择新旧程度");
            return;
        }
        Loading.show();
        //config配置上传参数
        Configuration configuration = new Configuration.Builder()
                .connectTimeout(10)
                .responseTimeout(60).build();

        if (this.uploadManager == null) {
            this.uploadManager = new UploadManager(configuration);
        }

        UploadOptions opt = new UploadOptions(null, null, true, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {
                LogUtils.e("qiniutest", "percent:" + percent);
            }
        }, null);
       String filename = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        this.uploadManager.put(file, filename, uploadToken,
                (key, respInfo, jsonData) -> {
                    if (respInfo.isOK()) {
                        SetSendData(add_name_edit.getText().toString().trim(),
                                TypeIndex, UsageTypeIndex, (BaseContest.QiNiuImage + filename),
                                add_remarks_edit.getText().toString().trim(),
                                Float.parseFloat(add_account_edit.getText().toString().trim()));
                    } else {
                        ToastUtils.showShort("上传图片失败");
                        Loading.dismiss();
                    }
                }, opt);
    }


    private void SetSendData(String name, int classType, int usage, String photo,
                             String remarks, float account) {
        WeakHashMap<String, Object> objectMap = new WeakHashMap<>();
        objectMap.put("name", name);
        objectMap.put("classType", classType);
        objectMap.put("usage", usage);
        objectMap.put("photo", photo);
        objectMap.put("remarks", remarks);
        objectMap.put("account", account);
        OkHttpHelper mHttpHelper = OkHttpHelper.getInstance();
        mHttpHelper.post(UrlRouter.SendTransactUrl, String.class, objectMap, new BaseCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                Loading.dismiss();
            }

            @Override
            public void onSuccess(Response response, Object arg1) {
                Loading.dismiss();
                Toast.makeText(getActivity(), "发布成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFalse(Response response, String err_msg) {
                Loading.dismiss();
                Toast.makeText(getActivity(), err_msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {
                Loading.dismiss();
            }
        });
    }


}
